package com.ppc.controller.worker;

import com.ppc.constant.JwtClaimsConstant;
import com.ppc.context.BaseContext;
import com.ppc.dto.UserLoginVerifyCodeDTO;
import com.ppc.dto.WorkerChangeInfoDTO;
import com.ppc.dto.WorkerLoginDTO;
import com.ppc.entity.Tag;
import com.ppc.mapper.worker.WorkerMapper;
import com.ppc.properties.JwtProperties;
import com.ppc.result.PageResult;
import com.ppc.result.Result;
import com.ppc.service.WorkerService;
import com.ppc.utils.JwtUtil;
import com.ppc.vo.EmployerLoginVO;
import com.ppc.vo.WorkerInfoQueryVO;
import com.ppc.vo.WorkerLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工人相关接口
 *
 * @author Jeferry
 * @date 2023/12/20
 */
@Slf4j
@RestController
@Api(tags = "工人基础接口")
public class WorkerController {

  @Autowired
  private WorkerService workerService;
  @Autowired
  private JwtProperties jwtProperties;
  @Autowired
  private WorkerMapper workerMapper;
  @Autowired
  private RedisTemplate<String, String> redisTemplate;

  /**
   * 工人上传头像
   *
   * @param file
   * @return {@link Result }<{@link String }>
   * @description
   */
  @PostMapping("worker/upload_img")
  @ApiOperation("工人上传头像")
  public Result<Long> uploadImg(@RequestPart("file") MultipartFile file) {
    log.info("头像上传{}", file);
    Long fileId = workerService.uploadImg(file);

    return Result.success(fileId);

  }

  /**
   * 工人登录
   *
   * @param workerLoginDTO 工人登录参数
   * @return {@link Result}<{@link WorkerLoginVO}>
   */
  @PostMapping("/worker/login")
  @ApiOperation("工人登录")
  public Result<WorkerLoginVO> login(@RequestBody WorkerLoginDTO workerLoginDTO) {
    log.info("工人登录：{}", workerLoginDTO);
    //调用service层来进行登录
    WorkerLoginVO worker = workerService.login(workerLoginDTO);
    //登录成功后，生成jwt令牌
    Map<String, Object> claims = new HashMap<>();
    claims.put(JwtClaimsConstant.WORKER_ID, worker.getUserID());
    String token = JwtUtil.createJWT(
        jwtProperties.getWorkerSecretKey(),
        jwtProperties.getWorkerTtl(),
        claims);
    worker.setToken(token);
    return Result.success(worker);
  }

  @PostMapping("/login_verify")
  @ApiOperation(value = "雇主验证码登录")
  public Result<WorkerLoginVO> loginVerfiyCode(@RequestBody UserLoginVerifyCodeDTO userLoginVerifyCodeDTO) {
    log.info("雇主验证码登录：{}", userLoginVerifyCodeDTO);

    if(userLoginVerifyCodeDTO.getUserVerfiyCode()==null || userLoginVerifyCodeDTO.getUserVerfiyCode()==""){
      return Result.error("验证码为空");
    }
    else if (userLoginVerifyCodeDTO.getUserEmail()!=null && userLoginVerifyCodeDTO.getUserEmail()!=""){
      String verifycode = (String) redisTemplate.opsForValue().get(userLoginVerifyCodeDTO.getUserEmail());
      if(!verifycode.equals(userLoginVerifyCodeDTO.getUserVerfiyCode())){
        return Result.error("验证码错误");
      }
    }else if(userLoginVerifyCodeDTO.getUserPhone()!=null && userLoginVerifyCodeDTO.getUserPhone()!=""){
      String verifycode = (String) redisTemplate.opsForValue().get(userLoginVerifyCodeDTO.getUserPhone());
      if(!verifycode.equals(userLoginVerifyCodeDTO.getUserVerfiyCode())){
        return Result.error("验证码错误");
      }
    }else {
      return Result.error("错误输入");
    }

    //调用service层来进行登录
    WorkerLoginVO worker = workerService.loginVerfiy(userLoginVerifyCodeDTO);
    //登录成功后，生成jwt令牌
    Map<String, Object> claims = new HashMap<>();
    claims.put(JwtClaimsConstant.WORKER_ID, worker.getUserID());
    String token = JwtUtil.createJWT(
        jwtProperties.getWorkerSecretKey(),
        jwtProperties.getWorkerTtl(),
        claims);
    worker.setToken(token);
    return Result.success(worker);


  }


  /**
   * 工人退出
   *
   * @return {@link Result}<{@link String}>
   */
  @PostMapping("/worker/logout")
  @ApiOperation("工人退出")
  public Result<String> logout() {
    log.info("工人退出");
    return Result.success();
  }

//   @GetMapping("/worker/credit")
//   @ApiOperation("查看信誉")
//   public Result<List<WorkerCreditVO>>checkCredit()
//   {
//     Long currentId = BaseContext.getCurrentId();
//     Long workerid = workerMapper.getCurrentWorkerId(currentId);
//     log.info("查看工人参与项目的信誉:{}",workerid);
//       //调用service层来获取返回结果
//       List<WorkerCreditVO> workers = workerService.checkCredit(Math.toIntExact(workerid));
//       return Result.success(workers);
//   }

  /**
   * 工人查看个人信息
   *
   * @return {@link Result}<{@link WorkerInfoQueryVO}>
   */
  @GetMapping("/worker/info/view")
  @ApiOperation("工人查看个人信息")
  public Result<WorkerInfoQueryVO> queryInformation() {
    Long currentId = BaseContext.getCurrentId();
    Long workerid = workerMapper.getCurrentWorkerId(currentId);
    log.info("查看工人工人信息:{}", workerid);
    WorkerInfoQueryVO worker = workerService.queryInformation(Math.toIntExact(workerid));
    return Result.success(worker);
  }

  /**
   * 工人修改个人信息
   *
   * @param workerChangeInfoDTO 工人修改个人信息参数
   * @return {@link Result}
   */
  @PostMapping("/worker/info/change")
  @ApiOperation("工人修改个人信息")
  public Result changeInformation(@RequestBody WorkerChangeInfoDTO workerChangeInfoDTO) {
    log.info("修改工人工人信息:{}", workerChangeInfoDTO);
    workerService.changeInformation(workerChangeInfoDTO);
    return Result.success();
  }

  /**
   * 工人修改自己标签
   *
   * @param tagNameList 工人修改自己标签列表
   * @return {@link Result}
   */
  @PostMapping("/worker/tag/change")
  @ApiOperation("工人修改自己标签")
  public Result changeTag(@RequestBody List<Integer> tagNameList) {
    log.info("工人修改自己的标签");
    workerService.changeTag(tagNameList);
    return Result.success();
  }

  /**
   * 工人增加自己标签
   *
   * @param tagId 标签id
   * @return {@link Result}
   */
  @GetMapping("/worker/tag/add")
  @ApiOperation("增加工人标签")
  public Result addTag(Integer tagId) {
    log.info("工人增加自己的标签");
    workerService.addTag(tagId);
    return Result.success();
  }

  /**
   * 工人删除自己标签
   *
   * @param tagId 标签id
   * @return {@link Result}
   */
  @GetMapping("/worker/tag/delete")
  @ApiOperation("删除工人标签")
  public Result deleteTag(Integer tagId) {
    log.info("工人删除自己的标签");
    workerService.deleteTag(tagId);
    return Result.success();
  }


  /**
   * 工人展示自己标签
   *
   * @param page 页码
   * @param pageSize 页大小
   * @return {@link Result}<{@link PageResult}>
   */
  @GetMapping("/worker/tag/show")
  @ApiOperation("展示工人标签")
  public Result<PageResult> showMyTags(Integer page, Integer pageSize) {
    log.info("工人展示自己所有标签及信息");
    PageResult p = workerService.showMyTags(page,pageSize);
    return Result.success(p);
  }

  /**
   * 工人展示所有标签
   *
   * @param page     页码
   * @param pageSize 页大小
   * @return {@link Result}<{@link PageResult}>
   */
  @GetMapping("worker/tag/showAll")
  @ApiOperation("展示所有标签")
  public Result<PageResult> showAllTags(Integer page, Integer pageSize) {
    log.info("展示所有已经存在的标签并分页展示");
    PageResult p = workerService.selectAllTags(page, pageSize);
    return Result.success(p);
  }

  /**
   * 工人展示所有有关信誉的日志
   *
   * @return {@link Result}<{@link List}<{@link String}>>
   */
  @GetMapping("worker/recording/credit")
  @ApiOperation("展示所有有关信誉的日志")
  public Result<List<String>> showRecordingCredit() {
    log.info("展示所有有关信用的日志");
    List<String> list = workerService.showRecordingCredit();
    return Result.success(list);
  }

  /**
   * 工人展示所有有关金钱的日志
   *
   * @return {@link Result}<{@link List}<{@link String}>>
   */
  @GetMapping("worker/recording/money")
  @ApiOperation("展示所有有关金钱的日志")
  public Result<List<String>> showRecordingMoney() {
    log.info("展示所有有关信用的日志");
    List<String> list = workerService.showRecordingMoney();
    return Result.success(list);
  }

  /**
   * 工人注销账户
   *
   * @return {@link Result}
   */
  @GetMapping("worker/logoff")
  @ApiOperation("注销账户")
  public Result logOffAccount() {
    log.info("工人注销账户");
    workerService.logOffAccount();
    return Result.success();
  }

  /**
   * 工人提现
   *
   * @param money
   * @return {@link Result}
   */
  @GetMapping("worker/cashwithdrawl")
  @ApiOperation("工人提现")
  public Result cashWithdrawal(Float money) {
    log.info("工人提现:{}", money);
    workerService.cashWithdrawal(money);
    return Result.success();
  }

}
